package vip.gnloypp.easy.multimedia.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import vip.gnloypp.easy.multimedia.data.dto.ReturnMessage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;


public class MultimediaRuntimeUtils {

    private static final Logger log = LogManager.getLogger(MultimediaRuntimeUtils.class);
    private static final String RUN_CMD = "执行命令：";
    private static final String RUN_CMD_FAILURE = "执行命令失败";
    private static final String READ_FAILURE_INFO_FAILURE = "读取错误信息失败";
    private static final String READ_SUCCESSFUL_INFO_FAILURE = "读取成功信息失败";

    private MultimediaRuntimeUtils() {
    }

    /**
     * 执行cmd命令,返回成功失败信息
     */
    public static String exec(String command) {
        log.info(RUN_CMD + command);
        try {
            Process exec = Runtime.getRuntime().exec(command);
            CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> {
                try {
                    return successful(exec);
                } catch (IOException e) {
                    throw new RuntimeException(READ_SUCCESSFUL_INFO_FAILURE, e);
                }
            });
            CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> {
                try {
                    return failureWarn(exec);
                } catch (IOException e) {
                    throw new RuntimeException(READ_FAILURE_INFO_FAILURE, e);
                }
            });
            // f1和f2执行完后执行f3
            CompletableFuture<ReturnMessage> f3 = f1.thenCombine(f2, (r1, r2) -> new ReturnMessage(r1, r2));
            ReturnMessage returnMessage = f3.join();
            int i = exec.waitFor();
            if (i != 0) {
                throw new RuntimeException(returnMessage.getErrorMsg());
            }
            return returnMessage.getMsg();
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(RUN_CMD_FAILURE, e);
        }
    }

    /**
     * 获取执行成功结果
     */
    private static String successful(Process exec) throws IOException {
        InputStream is = exec.getInputStream();
        return response(is);
    }

    /**
     * 获取执行失败结果
     */
    private static String failure(Process exec) throws IOException {
        InputStream is = exec.getErrorStream();
        return response(is);
    }

    /**
     * 获取执行失败结果
     */
    private static String failureWarn(Process exec) throws IOException {
        String failure = failure(exec);
        if (Objects.nonNull(failure) && failure.length() > 0) {
            log.warn(failure);
        }
        return failure;
    }

    /**
     * 打印执行结果
     */
    private static String response(InputStream is) throws IOException {
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        StringBuilder r = new StringBuilder();
        while ((line = br.readLine()) != null) {
            r.append(line + "\n");
        }
        return r.toString();
    }

}
